#!/bin/bash

set -e

# 检查软链接是否存在，不存在则创建
checkAndLink() {
    local checkPath="$2"
    local linkPath="$1"

    if [ -L $checkPath ]; then
        # 是符号链接，删除
        rm $checkPath
    elif [ -e $checkPath ]; then
        # 其他类型文件，需要人工确认删除
        echo "Error: There is a file at the link destination:"
        echo "    $checkPath"
        echo "Please remove it manually."
        exit 1
    fi

    # 进行链接
    ln -s $linkPath $checkPath
}

checkAndLink /opt/starkylin_connectivity/connectivity_softbus_server /usr/bin/connectivity_softbus_server
checkAndLink /opt/starkylin_connectivity/connectivity_softbus_client /usr/bin/connectivity_softbus_client
checkAndLink /opt/starkylin_connectivity/connectivity /usr/bin/connectivity
checkAndLink /opt/starkylin_connectivity/starkylin_connectivity_service /usr/bin/starkylin_connectivity_service

# 修改权限以能执行
chmod +555 /opt/starkylin_connectivity/connectivity_softbus_server
chmod +555 /opt/starkylin_connectivity/connectivity_softbus_client
chmod +555 /opt/starkylin_connectivity/starkylin_connectivity_service
chmod +777 /usr/bin/connectivity_softbus_server

# 获取用户名和用户组
user_info=$(getent passwd "$SUDO_USER")
primary_group_id=$(echo "$user_info" | cut -d: -f4)
primary_group_name=$(getent group "$primary_group_id" | cut -d: -f1)

sed -i "s/User_Placeholder/$SUDO_USER/g" /etc/systemd/system/starkylin_connectivity.service
sed -i "s/Group_Placeholder/$primary_group_name/g" /etc/systemd/system/starkylin_connectivity.service

systemctl daemon-reload
systemctl enable starkylin_connectivity.service
systemctl restart starkylin_connectivity.service